package com.sanuo.pico.view;

import static com.menu.app.activity.base.MenuBaseActivity.pointDlg;
import static com.menu.app.activity.base.MenuBaseActivity.showPointAlert;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.media.AudioManager;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;

import com.menu.app.MyApp;
import com.menu.app.activity.BaseBoardActivity;
import com.menu.app.activity.ChargeActivity;
import com.menu.app.activity.base.MenuBaseActivity;
import com.menu.app.activity.base.PortBaseActivity;
import com.menu.app.databinding.PopVolumeBinding;
import com.menu.app.db.bean.Doc;
import com.menu.app.event.work.PointEvent;
import com.menu.app.fragment.AlertDlg;
import com.menu.app.it.PopMenu;
import com.menu.app.model.Models;
import com.menu.app.ui.MaxWidthTextView;
import com.menu.app.util.Constant;
import com.menu.app.util.Enjoy;
import com.menu.app.util.Sys;
import com.menu.app.util.Utils;
import com.plata.base.aclr.utils.SPHelper;
import com.plata.base.utils.WeakHandler;
import com.sanuo.pico.R;
import com.sanuo.pico.databinding.PopMenuBinding;
import com.sanuo.pico.it.WorkingPage;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyPopMenu implements PopMenu {

    PopMenuBinding menuBinding;
    final int height = Utils.dipToPx(100);
    int start = -Utils.dipToPx(85);
    WeakHandler h = new WeakHandler(Looper.getMainLooper());

    public MyPopMenu() {
        if (Enjoy.isShowNavi()) {
            start += getNavigationBarHeight();
        }
    }

    public int getNavigationBarHeight() {
        Resources resources = MyApp.getApp().getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return resources.getDimensionPixelSize(resourceId);
        }
        return 0;
    }

    @Override
    public void addMenu(PortBaseActivity activity, boolean isVertical) {
        menuBinding = PopMenuBinding.inflate(LayoutInflater.from(activity));
        FrameLayout frame = (FrameLayout) activity.getWindow().getDecorView();
        FrameLayout.LayoutParams params;
        params = new FrameLayout.LayoutParams(Utils.getScreenWidth(), height);
        params.gravity = Gravity.BOTTOM;
        params.bottomMargin = start;
        frame.addView(menuBinding.getRoot(), params);

        menuBinding.home2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideMenu.run();
                checkLeave(activity, () -> activity.back2Board());
            }
        });
        menuBinding.cusLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideMenu.run();
                checkLeave(activity, new Runnable() {
                    @Override
                    public void run() {
                        activity.beforeJump(new MenuBaseActivity.JumpPrepareListener() {
                            @Override
                            public void onPrepared() {
                                Intent i = new Intent(activity, MyApp.getApp().getCustomInfoClass());
                                i.putExtra("custom", BaseBoardActivity.custom);
                                i.putExtra("board", activity instanceof BaseBoardActivity);
                                activity.startActivity(i);
                            }
                        });
                    }
                });
            }
        });
        menuBinding.wifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //    Intent it = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                hideMenu.run();
                checkLeave(activity, new Runnable() {
                    @Override
                    public void run() {
                        h.post(new Runnable() {
                            @Override
                            public void run() {
                                Sys.toWifi(activity, -1);
                            }
                        });
                    }
                });
            }
        });

        menuBinding.blue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideMenu.run();
                checkLeave(activity, new Runnable() {
                    @Override
                    public void run() {
                        h.post(new Runnable() {
                            @Override
                            public void run() {
                                Utils.showBluetoothSetting();
                            }
                        });
                    }
                });
            }
        });
        menuBinding.volume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopVolume(activity);
                h.removeCallbacks(hideMenu);
            }
        });
        menuBinding.timeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideMenu.run();
                checkLeave(activity, new Runnable() {
                    @Override
                    public void run() {
                        h.post(new Runnable() {
                            @Override
                            public void run() {
                                activity.startActivity(new Intent(android.provider.Settings.ACTION_DATE_SETTINGS));
                            }
                        });
                    }
                });
            }
        });

        menuBinding.pointLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideMenu.run();
                checkLeave(activity, new Runnable() {
                    @Override
                    public void run() {
                        activity.beforeJump(new MenuBaseActivity.JumpPrepareListener() {
                            @Override
                            public void onPrepared() {
                                Intent intent = new Intent(activity, ChargeActivity.class);
                                activity.startActivity(intent);
                            }
                        });
                    }
                });
            }
        });

        h.post(runnable);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            int w = menuBinding.users.getWidth();
            if (w == 0) {
                h.postDelayed(this, 200);
            } else {
                w *= 0.4;
                View v = menuBinding.name;
                if (v instanceof MaxWidthTextView) {
                    ((MaxWidthTextView) v).setMaxWidth(w);
                }
                v = menuBinding.cusName;
                if (v instanceof MaxWidthTextView) {
                    ((MaxWidthTextView) v).setMaxWidth(w);
                }
            }
        }
    };

    boolean moving = false;
    boolean show = false;

    final ValueAnimator.AnimatorUpdateListener listener = new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(@NonNull ValueAnimator animation) {
            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) menuBinding.getRoot().getLayoutParams();
            int currentValue = (Integer) animation.getAnimatedValue();
            params.bottomMargin = currentValue;
            menuBinding.getRoot().setLayoutParams(params);
        }
    };

    private int getBase() {
        if (Constant.MENU_GRAVITY == Gravity.BOTTOM && Enjoy.isShowNavi()) {
            return getNavigationBarHeight();
        }
        return 0;
    }

    private void animateIn() {
        ValueAnimator valueAnimator = ValueAnimator.ofInt(start, getBase());
        valueAnimator.addUpdateListener(listener);
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                moving = false;
                show = true;
                h.removeCallbacks(hideMenu);
                h.postDelayed(hideMenu, 5000);
            }
        });
        valueAnimator.setDuration(300);
        valueAnimator.start();
    }

    private void animateOut() {
        ValueAnimator valueAnimator = ValueAnimator.ofInt(getBase(), start);
        valueAnimator.addUpdateListener(listener);
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                moving = false;
                show = false;
            }
        });
        valueAnimator.setDuration(300);
        valueAnimator.start();
    }

    Runnable hideMenu = new Runnable() {
        @Override
        public void run() {
            hidePopWin();
        }
    };

    @Override
    public final void hidePopWin() {
        if (moving || !show) {
            return;
        }
        h.removeCallbacks(updateTime);
        moving = true;
        animateOut();
    }

    Runnable updateTime = new Runnable() {
        @Override
        public void run() {
            String[] ss = timeStr();
            menuBinding.time.setText(ss[1]);
            menuBinding.date.setText(ss[0]);
            h.postDelayed(this, 1000);
        }
    };

    private String[] timeStr() {
        Date d = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat(Utils.isRu() ? "dd/MM/yyyy HH:mm" : "yyyy/MM/dd HH:mm");
        String str = sdf.format(d);
        return str.split(" ");
    }

    @Override
    public void showPopWin(MenuBaseActivity activity) {
        if (moving || show || activity.isLoading()) {
            return;
        }
        Doc doc = MyApp.getApp().getDoc();
        if (doc == null || doc.anonymous) {
            menuBinding.docLayout.setVisibility(View.INVISIBLE);
        } else {
            menuBinding.docLayout.setVisibility(View.VISIBLE);
            try {
                Utils.setImage(MyApp.getApp().getDoc().header, menuBinding.header);
                ((TextView) menuBinding.name).setText(MyApp.getApp().getDoc().name);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        if (BaseBoardActivity.custom != null) {
            menuBinding.cusLayout.setVisibility(View.VISIBLE);
            Utils.setImage(BaseBoardActivity.custom.header, menuBinding.cusHeader);
            ((TextView) menuBinding.cusName).setText(BaseBoardActivity.custom.name);
        } else {
            menuBinding.cusLayout.setVisibility(View.GONE);
        }
        menuBinding.wifi.refresh();
        try {
            if (BluetoothAdapter.getDefaultAdapter().getState() == BluetoothAdapter.STATE_ON) {
                menuBinding.blue.setImageResource(com.menu.app.R.mipmap.bluetooth);
            } else {
                menuBinding.blue.setImageResource(com.menu.app.R.mipmap.blue_close);
            }
        } catch (Throwable e) {
            e.printStackTrace();
            menuBinding.blue.setImageResource(com.menu.app.R.mipmap.blue_close);
        }

        AudioManager mAudioManager = (AudioManager) MyApp.getApp()
                .getSystemService(Context.AUDIO_SERVICE);
        int current = mAudioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
        if (current == 0) {
            menuBinding.volume.setImageResource(com.menu.app.R.mipmap.volume_off);
        } else {
            menuBinding.volume.setImageResource(com.menu.app.R.mipmap.volumn);
        }
        if (activity.showHome()) {
            menuBinding.home2.setVisibility(View.VISIBLE);
        } else {
            menuBinding.home2.setVisibility(View.GONE);
        }
        if (activity.showUsrs() && (menuBinding.docLayout.getVisibility() == View.VISIBLE || menuBinding.cusLayout.getVisibility() == View.VISIBLE)) {
            menuBinding.users.setVisibility(View.VISIBLE);
        } else {
            menuBinding.users.setVisibility(View.GONE);
        }
        menuBinding.temp.setText(String.valueOf(Models.Companion.get().getTempEvent().getValue()));
        menuBinding.flow.setText(String.valueOf(Models.Companion.get().getFlowEvent().getValue()));

        updatePoint(true, Models.Companion.get().getPointEvent(), activity);
        updateTime.run();
        moving = true;
        animateIn();
    }

    private void checkLeave(FragmentActivity activity, Runnable runnable) {
        if (MyApp.getApp().isWorkingPage(activity) && ((WorkingPage) activity).isWorking()) {
            AlertDlg dlg = new AlertDlg().setMessage(activity.getString(R.string.stop_work)).showCancelBtn(false);
            dlg.show(activity.getSupportFragmentManager(), "tip");
        } else {
            runnable.run();
        }
    }

    @Override
    public void updatePoint(boolean create, PointEvent event, FragmentActivity activity) {
        if (!Models.Companion.get().getStartEvent().getValue()) {
            setPointVisibility(View.INVISIBLE);
            return;
        }
        boolean rent = Models.Companion.get().getRentEvent().getValue() == 1;
        if (!rent) {
            if (pointDlg != null) {
                pointDlg.dismiss();
            }
        } else {
            if (!create && event.getValue() != Long.MIN_VALUE && event.getValue() <= 0) {
                showPointAlert(activity);
            } else if (pointDlg != null && event.getValue() > 0) {
                pointDlg.dismiss();
            }
        }
        if (create || show) {
            menuBinding.point.setText(String.valueOf(event.getValue()));
            if (event.getValue() == Long.MIN_VALUE
                    || !rent) {
                setPointVisibility(View.INVISIBLE);
            } else {
                setPointVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void setPointVisibility(int flag) {
        if (menuBinding == null || menuBinding.pointLayout == null) {
            return;
        }
        long time = SPHelper.getInstance(MyApp.getApp()).getLong("end_time", 0);
        if (time > 0) {
            flag = View.VISIBLE;
            menuBinding.point.setText(Utils.getDay4(time));
        }
        menuBinding.pointLayout.setVisibility(flag);
    }

    @Override
    public void updateTemperature(String str) {
        if (show) {
            menuBinding.temp.setText(str);
        }
    }

    @Override
    public void updateFlow(String str) {
        if (show) {
            menuBinding.flow.setText(str);
        }
    }

    PopupWindow volumePop;
    PopVolumeBinding popVolumeBinding;

    Runnable hideVolume = new Runnable() {
        @Override
        public void run() {
            try {
                if (volumePop == null || !volumePop.isShowing()) {
                    return;
                }
                volumePop.dismiss();
                h.removeCallbacks(this);
            } finally {
                h.removeCallbacks(hideMenu);
                h.postDelayed(hideMenu, 5000);
            }
        }
    };


    private void play() {
        Utils.prepareAudioPlayer();
    }

    private void showPopVolume(FragmentActivity activity) {
        int type = AudioManager.STREAM_NOTIFICATION;
        AudioManager mAudioManager = (AudioManager) activity
                .getSystemService(Context.AUDIO_SERVICE);
        int current = mAudioManager.getStreamVolume(type);
        if (volumePop == null) {
            int VOLUME_MAX = mAudioManager
                    .getStreamMaxVolume(type);
            popVolumeBinding = DataBindingUtil.inflate(LayoutInflater.from(activity), com.menu.app.R.layout.pop_volume, null, false);
            popVolumeBinding.fullPlaySeekbar.setMax(VOLUME_MAX);
            popVolumeBinding.fullPlaySeekbar.setProgress(current);
            popVolumeBinding.fullPlaySeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                int progress = -1;

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    this.progress = progress;

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    h.removeCallbacks(hideVolume);
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    if (this.progress >= 0) {
                        if (progress > 0) {
                            menuBinding.volume.setImageResource(com.menu.app.R.mipmap.volumn);
                        } else {
                            menuBinding.volume.setImageResource(com.menu.app.R.mipmap.volume_off);
                        }
                        mAudioManager.setStreamVolume(type, progress, 0);
                        play();
                    }
                    h.removeCallbacks(hideVolume);
                    h.postDelayed(hideVolume, 5000);
                }
            });
            volumePop = new PopupWindow();
            volumePop.setOutsideTouchable(true);
            volumePop.setTouchable(true);
            volumePop.setContentView(popVolumeBinding.getRoot());
            int h = (int) (Utils.getScreenHeight() * 0.3);
            int w = (int) (42f / 312 * h);
            volumePop.setWidth(w);
            volumePop.setHeight(h);
        }
        popVolumeBinding.fullPlaySeekbar.setProgress(current);
        if (!volumePop.isShowing()) {
            volumePop.showAtLocation(activity.getWindow().getDecorView(), Gravity.BOTTOM, (int) (0.43 * Utils.getScreenWidth()), -(int) (start * 0.8));
            h.removeCallbacks(hideVolume);
            h.postDelayed(hideVolume, 5000);
        }
    }

    @Override
    public void hidePop() {
        if (volumePop != null && volumePop.isShowing()) {
            volumePop.dismiss();
        }
        hidePopWin();
    }
}
